package com.zh.harmony.viewmodel;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * ViewModelStore，保存ViewModel的仓库
 */
public class ViewModelStore {
    /**
     * 保存容器，Key-Value形式
     */
    private final HashMap<String, ViewModel> mMap = new HashMap<>();

    /**
     * 保存ViewModel
     */
    final void put(String key, ViewModel viewModel) {
        ViewModel oldViewModel = mMap.put(key, viewModel);
        if (oldViewModel != null) {
            oldViewModel.onCleared();
        }
    }

    /**
     * 获取ViewModel
     */
    final ViewModel get(String key) {
        return mMap.get(key);
    }

    /**
     * 获取所有ViewModel的Key
     */
    Set<String> keys() {
        return new HashSet<>(mMap.keySet());
    }

    /**
     * 清除所有ViewModel，并通知每个ViewModel应该被销毁
     */
    public final void clear() {
        for (ViewModel vm : mMap.values()) {
            vm.clear();
        }
        mMap.clear();
    }
}